<template>
    <div class="topbar">
        <div class="tab-container">
            <div class="top-tabs" @wheel.prevent="handleWheelTabs" @mousedown.stop="handleScrollTabbar">
                <div class="top-tab-item" v-for="tab in tabs" :key="tab.id" :title="tab.name" :data-tabid="tab.id">
                    <i :class="['diconfont', tab.icon]" :data-tabid="tab.id"></i>
                    <span :data-tabid="tab.id">{{tab.name}}</span>
                    <i @click.stop.event="deleteTab(tab.id)" class="el-icon-close icon-item-close" title="删除连接"></i>
                </div>
            </div>
            <div class="topbar-mover" @mousedown.stop="handleMouseDown"></div>
        </div>
        <div class="topbar-buttons">
            <span title="新建连接" @click="toggleLoginDialog">
                <i class="diconfont dicon-plus"></i>
            </span>
            <span @click.stop="changeWindowState('minimum')">
                <i class="diconfont dicon-minus"></i>
            </span>
            <span @click.stop="changeWindowState('maximum')">
                <i :class="['diconfont', maximize ? 'dicon-maximum' : 'dicon-maximum1']"></i>
            </span>
            <span @click.stop="changeWindowState('close')" class="topbar-btn-close">
                <i class="diconfont dicon-close"></i>
            </span>
        </div>
    </div>
</template>

<script>
    import {mapActions} from 'vuex'

    export default {
        name: "Topbar",

        data() {
            return {
                maximize: false,
                tabs: [
                    {id: '1', name: 'Oracle-192.168.1.9:1521@orcl', icon: 'dicon-oracle',},
                    {id: '2', name: 'MySQL-127.0.0.1:3306@root', icon: 'dicon-mysql',},
                    {id: '3', name: 'SQLServer-127.0.0.1:1433@sa', icon: 'dicon-sqlserver',},
                ],
            }
        },

        methods: {
            ...mapActions(['toggleLoginDialog']),

            /**
             * 拖动标题栏移动窗口位置
             * @param {MouseEvent} event
             */
            handleMouseDown(event) {
                let [x, y] = this.$mainWindow.getPosition();
                let {screenX, screenY} = event;

                const handleMouseMove = evt => {
                    if (this.$mainWindow.isMaximized()) {
                        return;
                    }
                    let {screenX: moveScreenX, screenY: moveScreenY} = evt;
                    let movedX = moveScreenX - screenX;
                    let movedY = moveScreenY - screenY;

                    x += movedX;
                    y += movedY;

                    this.$mainWindow.setPosition(x, y);
                    screenX = moveScreenX;
                    screenY = moveScreenY;
                };

                const handleMouseUp = () => {
                    document.removeEventListener('mousemove', handleMouseMove);
                    document.removeEventListener('mouseup', handleMouseUp);
                };

                document.addEventListener('mousemove', handleMouseMove);
                document.addEventListener('mouseup', handleMouseUp);
            },

            /**
             * 鼠标横向拖动标签栏
             * @param {MouseEvent} event
             */
            handleScrollTabbar: function (event) {
                if (event.button !== 0) {
                    return;
                }
                const currentTarget = event.currentTarget;
                const target = event.target;
                let {clientX} = event;
                let originClientX = clientX;

                const handleMouseMove = evt => {
                    let {clientX: moveClientX} = evt;
                    currentTarget.scrollLeft -= moveClientX - clientX;
                    clientX = moveClientX;
                };

                const handleMouseUp = () => {
                    document.removeEventListener('mousemove', handleMouseMove);
                    document.removeEventListener('mouseup', handleMouseUp);

                    // 鼠标移动距离小于5px时，手动触发click事件
                    let movedX = Math.abs(originClientX - clientX);
                    if (movedX < 5 && target.dataset.tabid !== undefined) {
                        const currentItem = this.$el.querySelector('.top-tab-item.on');
                        if (currentItem) {
                            currentItem.classList.remove('on');
                        }
                        target.parentNode.classList.add('on');
                        this.handleTabItemClick(target.dataset.tabid);
                    }
                };

                document.addEventListener('mousemove', handleMouseMove);
                document.addEventListener('mouseup', handleMouseUp);
            },

            /**
             * 鼠标滚轮滚动横向滚动标签栏
             * @param {WheelEvent} e
             */
            handleWheelTabs(e) {
                let step = 60;
                if (e.deltaY > 0) {
                    // 鼠标滚轮向下滚动
                    e.currentTarget.scrollLeft += step;
                } else {
                    // 鼠标滚轮向上滚动
                    e.currentTarget.scrollLeft -= step;
                }
            },

            /**
             * 改变窗口状态
             * @param state
             */
            changeWindowState(state) {
                switch (state) {
                    case 'maximum':
                        this.$mainWindow.isMaximized() ? this.$mainWindow.unmaximize() : this.$mainWindow.maximize();
                        break;
                    case 'minimum':
                        this.$mainWindow.minimize();
                        break;
                    case 'close':
                        this.$mainWindow.close();
                        break;
                }
            },

            /**
             * 点击tab项
             * @param tabId tab id
             */
            handleTabItemClick(tabId) {
                const tab = this.tabs.find(t => t.id === tabId);
                // console.log(tab);
            },

            /**
             * 删除Tab项
             * @param tabId
             */
            deleteTab(tabId) {
                let index = this.tabs.findIndex(item => item.id === tabId);
                if (index !== -1) {
                    this.tabs.splice(index, 1);
                }
            },

            handleTabContextMenu() {
                this.$contextmenu([]);
            },
        },

        mounted() {
            this.$mainWindow.on('maximize', () => {
                this.maximize = true;
            });
            this.$mainWindow.on('unmaximize', () => {
                this.maximize = false;
            });
        },
    }
</script>

<style scoped lang="scss">
    $size: 32px;
    $scrollbar-size: 17px;

    .topbar {
        height: $size;
        display: flex;
        align-items: center;
        justify-content: space-between;
        background: #000;
        color: #fff;
        box-shadow: 0 0 12px 1px #000;
        width: 100%;
        user-select: none;

        .tab-container {
            height: 100%;
            width: calc(100% - #{$size} * 4);
            position: relative;
            overflow: hidden;
            flex: 1;
        }

        .top-tabs {
            position: relative;
            z-index: 2;
            height: calc(100% + #{$scrollbar-size});
            max-width: 100%;
            overflow-x: scroll;
            overflow-y: hidden;
            display: inline-flex;
            transition: all .2s;

            .top-tab-item {
                position: relative;
                height: $size;
                display: inline-flex;
                align-items: center;
                justify-content: flex-start;
                font-size: 12px;
                max-width: 220px;
                box-sizing: border-box;
                padding: 0 5px;
                cursor: default;
                transition: all .2s;

                &.on {
                    background: #fff;
                    box-shadow: 0 0 12px 1px #fff;

                    > span {
                        color: #f00;
                    }
                }
                &:hover {

                    > .icon-item-close {
                        display: inline-flex;
                    }
                }

                > i {
                    display: inline-flex;
                    height: 100%;
                    width: $size;
                    align-items: center;
                    justify-content: center;
                }

                > span {
                    display: inline-flex;
                    align-items: center;
                    justify-content: flex-start;
                    height: 100%;
                    white-space: nowrap;
                    text-overflow: ellipsis;
                    overflow: hidden;
                }

                > .icon-item-close {
                    position: absolute;
                    right: 1px;
                    background: #fff;
                    color: $--color-danger;
                    width: 16px;
                    height: 16px;
                    border-radius: 50%;
                    box-shadow: 0 0 6px #fff;
                    display: none;
                    transition: all .5s;
                    align-items: center;
                    justify-content: center;
                }
            }
        }

        .topbar-mover {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
        }

        .topbar-buttons {
            display: flex;
            height: 100%;
            align-items: center;

            > span {
                height: 100%;
                display: inline-flex;
                align-items: center;
                justify-content: center;
                width: $size;

                &:hover {
                    background: rgba(#fff, .2);
                }

                &.topbar-btn-close:hover {
                    background: rgba(#f00, .7);
                }

                i {
                    font-size: 14px;
                }
            }
        }
    }
</style>
